/**
 * 版权声明：
 * 该项目及所有代码、配置都属于Rich所有，他人可以任意使用、修改、传播，但必须保证该声明的存在。
 */
package rich.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.junit.Test;

/**
 * @author Rich
 * 
 * @Date 2011-12-16
 * 
 */
public class TestSendAuthMail {

	private String mailhost = ".com";
	private String port = "465";
	private String from = ".com";
	private String to = ".com";
	private String userName = "";
	private String passwd = "";

	@Test
	public void testSendGamil() {
		try {
			sendMail("Hello JavaMail", "elcome to JavaMail", from, to);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private synchronized void sendMail(String subject, String body,
			String sender, String recipients) throws Exception {

		// Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", mailhost);
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.quitwait", "false");

		Session session = Session.getDefaultInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(userName, passwd);
					}
				});
		MimeMessage message = new MimeMessage(session);
		message.setSender(new InternetAddress(sender));
		message.setSubject(subject);
		message.setContent(body, "text/plain");
		if (recipients.indexOf(',') > 0)
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(recipients));
		else
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(
					recipients));

		Transport trans = session.getTransport("smtp");
		trans.connect(mailhost, Integer.parseInt(port), userName, passwd);
		trans.send(message);

	}

}
